#!/bin/bash

#v0.4 增加端口检测
#v0.5 修改jvm参数 
#v0.6 1）增加backupall目录，用于保存历史版本
#     2）增加jar推送的判断
#v0.7 增加ip地址提示，改写函数方式
#v1.00 增加脚本判断及更新机制
#v1.50 本地保存30天。
#v2.00 隐藏部分日志显示，全部日志写入日志文件中.
#v2.00 添加更改CMDB状态, 1,为发布成功; 2, 为发布中; 3, 为发布失败

export LANG="en_US.UTF-8"
source /etc/profile
baseDir="/opt/app/spring"
VerSion=1.20
KeepPeriod=30
portConfig="/opt/app/appPorts.properties"
logfile=$6


Setlog() {
    echo $1 >> $logfile
}

getPortConfig(){
  args=($@)
  echo `sed -n "/${arg1}=/"p ${portConfig} | sed "s/${arg1}=//"`
}


arg1=${2} 
export portStart="`getPortConfig`"
#arg1=${2}-stop
#export portStop="`getPortConfig`"

###更新CMDB App 状态

function SetStatus(){
    sid=$1
    LocalIP=`/sbin/ifconfig |grep "inet addr" |awk '{print $2}' |awk -F : '{print $2}' | grep -v '127.0.0.1'`
    curl -s -m 2 http://cmdb.bl.com/blapp/srelease/?sid=$sid\&appip=$LocalIP\&appport=$portStart\&operation=fabu-sit
    if [ $? -eq 0 ];then
        case $sid in
            1)
                echo "cmdb状态已更新为: 发布成功"
                Setlog "cmdb状态已更新为: 发布成功"
            ;;
            2)
                echo "cmdb状态已更新为: 发布中"
                Setlog "cmdb状态已更新为: 发布中"
            ;;
            3)
                echo "cmdb状态已更新为: 发布失败"
                Setlog "cmdb状态已更新为: 发布失败"
            ;;
            *)
                echo "参数传入错误,请检查!!!"
                Setlog "参数传入错误,请检查!!!"
        esac
    else
        echo "cmdb 修改失败,请检查!!!"
        Setlog "cmdb 修改失败,请检查!!!"
    fi
}



function PortsCheck()
{
echo "    |--->[√]启动端口号是:$portStart"
Setlog "    |--->[√]启动端口号是:$portStart"

echo "    |--->[√]关闭端口号是:$portStop"
Setlog "    |--->[√]关闭端口号是:$portStop"
if      
    [ ! $portStart  ]
      then     
        echo "[×]发布脚本获取${2}端口失败,请检查传参！本次发布被取消！无需回滚"
        Setlog "[×]发布脚本获取${2}端口失败,请检查传参！本次发布被取消！无需回滚"
        exit 1
fi
}

function CreateFolders()
{
if [ ! -d "${baseDir}/running/$1" ]
        then 
                mkdir -p ${baseDir}/running/$1
fi 

if [ ! -d "${baseDir}/temp/$1" ]
        then 
                mkdir -p ${baseDir}/temp/$1
fi 

#保存上次运行的版本
if [ ! -d "${baseDir}/backup/$1" ]
        then 
                mkdir -p ${baseDir}/backup/$1
fi 

#保存历史版本
if [ ! -d "${baseDir}/backupall/$1" ]
        then 
                mkdir -p ${baseDir}/backupall/$1
fi 
}

#function ShutdownProject()
#{
#kill -9 `cat ${baseDir}/running/$1/main.pid`
#Setlog "    |--->[√]关闭${2}系统成功..."
#}

function ShutdownProject()
{
processpid=`ps -ef | grep -v grep | grep -v $0 | grep java | grep ${1} | awk '{print $2}'`
if [ X"$processpid" != X ];then
    kill -9 $processpid
    if [ $? -eq 0 ];then
        echo "    |--->[√]关闭${2}系统成功..."
        Setlog "    |--->[√]关闭${2}系统成功..."
    else
        echo "关闭${2}系统失败，发布失败，不需要回滚!"
        Setlog "关闭${2}系统失败，发布失败，不需要回滚!"
        exit 1
    fi
else
    echo "进程不存在，请注意!!!"
    Setlog "进程不存在，请注意!!!"
fi
}

function MvProject()
{
Setlog "    |--->备份运行项目[$2]"
rm -rf ${baseDir}/backup/$1/*
mv ${baseDir}/running/$1/* ${baseDir}/backup/$1/
}

function DeployProject()
{
Setlog "    |--->开始部署新的代码到running目录"
cp -f ${baseDir}/temp/$1/*.jar ${baseDir}/running/$1/
echo "    |--->[$2]部署完成"
Setlog "|--->[$2]部署完成"
echo ""
}

function CompareProjectDate()
{
SourceJarDate=`stat $baseDir/temp/${1}/*.jar | grep Change | awk '{print $2}'|sed s/-//g`
TodayDate=`date '+%Y%m%d'`
Setlog "    |--->源包的时间是:$SourceJarDate"
Setlog "    |--->今天的时间是:$TodayDate"
if
        [ "$SourceJarDate" -eq "$TodayDate" ]
         then
                Setlog "        |--->[√]Jar包是今天生成的"
        else
                echo "        |--->[×]Jar包不是今天生成的，请注意！！！"
                Setlog "        |--->[×]Jar包不是今天生成的，请注意！！！"
fi
echo ""
}



function CompareProjectMd5()
{
SourceJarMd5=`/usr/bin/md5sum $baseDir/temp/${1}/*.jar  | awk '{print $1}'`
DestJarMd5=`/usr/bin/md5sum ${baseDir}/running/$1/*.jar  | awk '{print $1}'`
Setlog "    |--->编译完的包的MD5值是:$SourceJarMd5"
Setlog "    |--->计划发布包的MD5值是:$DestJarMd5"
if
    [ "$SourceJarMd5" = "$DestJarMd5" ]
  then
    Setlog "        |--->[√]计划发布的Jar包和本次编译的Jar包一样"
  else
    echo "        |--->[×]计划发布的Jar包和本次编译的Jar包不一样，请注意！！"
    Setlog "        |--->[×]计划发布的Jar包和本次编译的Jar包不一样，请注意！！"
    echo "        |--->[×]$2退出发布!!!本次发布被取消！需回滚!!!!!!!!!"
    Setlog "        |--->[×]$2退出发布!!!本次发布被取消！需回滚!!!!!!!!!"
    exit 1
fi
}

function StartProject()
{
Setlog "    |--->后台启动进程"
nohup java ${3} ${4} -Xss256K -XX:PermSize=256m -XX:MaxPermSize=512m -XX:+UseConcMarkSweepGC -XX:+UseParNewGC -XX:SurvivorRatio=3 -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/home/netty/jvmdump -jar $baseDir/running/$1/*.jar --spring.profiles.active=$5 --server.port=$portStart > /dev/null &
echo $! >  ${baseDir}/running/$1/main.pid
sleep 10
ps -ef | grep -v grep | grep -v $0 | grep java | grep $2 >> /dev/null
if [ $? -eq 0 ];then
    echo ""
    Setlog "        |--->[√]启动完成"
    echo "|--->[$2]启动完成"
else
    echo "|--->[$2] 启动失败,请注意!!!"
fi
echo ""
}


function CheckProjectStatus()
{
sleep 10
springPid=`cat ${baseDir}/running/$1/main.pid`
processIds=`ps -ef | grep $2\/ | grep -v grep  | grep java | grep -v $0 | awk '{print $2}'`
Setlog "    |--->当前[文件]中的PID是$springPid"
Setlog "    |--->当前[进程]中的PID是$processIds"
if
        [ "$springPid" -eq "$processIds" ]
         then
                Setlog "        |--->[√]$2服务已重启成功"
                echo "|--->[√]$2服务已重启成功"
        else
                echo "        |--->[×]$2服务重启异常，需手工重启....."
                Setlog "        |--->[×]$2服务重启异常，需手工重启....."
fi
echo ""
}

function Bakproject()
{
JarDate="`date '+%Y%m%d'`-`date '+%H%M%S'`"
Setlog "    |--->正在清除缓存目录..."
mv ${baseDir}/temp/$1 ${baseDir}/backupall/$1/$JarDate
Setlog "        |--->[√]缓存目录已移动至${baseDir}/backupall/$1/$JarDate"
for((i=$KeepPeriod;i<=365;i++));
	do
		Warnum1=`find  ${baseDir}/backupall/$1 -maxdepth 1 -mindepth 1 -mtime +$i | grep $2 | wc -l`
		Warnum2=`ls -l ${baseDir}/backupall/$1 | grep -v total | wc -l`
		#字符串转为数字
		War_num1_exp=`expr $Warnum1`
		War_num2_exp=`expr $Warnum2`
		#判断文件个数，不能全部删除备份。
		if [ $War_num1_exp -lt $War_num2_exp ]
		then 
			Setlog "    |--->开始清除$i天前目录..."
			Setlog `find  ${baseDir}/backupall/$1 -maxdepth 1 -mindepth 1 -mtime +$i`
			rm -rf `find  ${baseDir}/backupall/$1 -maxdepth 1 -mindepth 1 -mtime +$i`
			Setlog "    |--->[√]清理完成"
		fi
	break
done

}




Setlog "---->1.1 获取端口号..."
PortsCheck $1 $2
CreateFolders $1 $2

Setlog "---->1.2 关闭$2系统"
SetStatus 2
ShutdownProject $1 $2

Setlog "---->1.3 备份$2系统"
MvProject $1 $2

Setlog "---->1.4 部署新的代码"
DeployProject $1 $2

Setlog "---->1.5 判断jar包的生成日期"
CompareProjectDate $1 $2

Setlog "---->1.6 判断jar包的md5值"
CompareProjectMd5 $1 $2

#echo "---->1.7 开始运行服务"
echo "----> 开始运行服务[$2]"
StartProject $1 $2 $3 $4 $5
sleep 10

Setlog "---->1.8 检测$2进程状态"
CheckProjectStatus $1 $2

Setlog "---->1.9 备份、清理$2项目代码"
Bakproject $1 $2
sleep 1
